/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session;

import Entity.Magasin;
import java.util.List;
import javax.ejb.EJBException;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Gael
 */
@Stateless
public class BeanMagasin {

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    @PersistenceContext
    private EntityManager em;
    
    public Magasin creer(Magasin m){
        try{
            em.persist(m);
            return m;
        }catch(Exception e){
            System.err.print("Echec enregistrement magasin");
            return null;
        }
    } 
    
    public Magasin update(Magasin m){
        try{
            em.merge(m);
            return m;
        }catch(Exception e){
            System.err.print("Echec enregistrement magasin");
            return null;
        }
    }

    public List<Magasin> getAllMagasins() {
        Query query = em.createNamedQuery("Magasin.findAll");
        
        return query.getResultList();
    }
    
    public List<Magasin> getMagasinsByName(String key) {
        Query query = em.createNamedQuery("Magasin.findByName");
        query.setParameter("mot", "%" + key + "%");
        return query.getResultList();
    }
    
    public List<Magasin> getMagasinsByVille(String key) {
        Query query = em.createNamedQuery("Magasin.findByVille");
        query.setParameter("mot", "%" + key + "%");
        return query.getResultList();
    }
    
    public Magasin getMagasinById(long id){
        Query query = em.createNamedQuery("Magasin.findById");  
        query.setParameter("magasinid", id); 
        try{
            
            return (Magasin) query.getSingleResult(); 
        }catch(Exception e){
            System.err.println("ID inexistant");
            return null;
        }
    }
    public Magasin getMagasinbyVendeur(String p){
        Query query = em.createNamedQuery("Magasin.findByVendeur");  
        query.setParameter("Vendeur", p);  
        try{
           return (Magasin) query.getSingleResult();  
        }catch(Exception e){
            System.err.println("Erreur recherche proprietaire par nom :"+p+":");
            return null;
        }  
    }

    public void delete(Magasin m) {
        try{
            System.out.println("+++++Nom : "+m.getNom());
            Magasin store = this.getMagasinById(m.getId());
            em.remove(store);
        }
        catch(EJBException e){
            
            e.getStackTrace();
        }
    }
}
